<template>
  <div class="order-container">
    <h2  >订单查看</h2>
    <!-- 查询区域 -->
    <div class="search-container">
      <el-select
          v-model="queryOrderStatus"
          placeholder="全部"
          style="width: 160px"
      >
        <el-option label="全部" value=""/>
        <el-option label="制作中" value="制作中"/>
        <el-option label="待取餐" value="待取餐"/>
        <el-option label="已完成" value="已完成"/>
      </el-select>

      <div class="date-range">
        <el-date-picker
            v-model="startTime"
            type="datetime"
            placeholder="开始时间"
            style="width: 100%"
        />
        <span class="date-separator">至</span>
        <el-date-picker
            v-model="endTime"
            type="datetime"
            placeholder="结束时间"
            style="width: 100%"
        />
      </div>

      <el-button @click="goToScreen" type="info">大屏叫号</el-button>
      <el-button @click="queryOrders" type="success">查询</el-button>
    </div>

    <!-- 错误提示 -->
    <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>

    <!-- 订单表格 -->
    <div class="table-wrapper">
      <el-table
          :data="orderList"
          border
          stripe
          empty-text="暂无订单数据"
          max-height="calc(100vh - 260px)"
          style="width: 100%"
      >
<!--        <el-table-column label="序号" type="index" width="60" align="center"/>-->
        <el-table-column prop="id" label="订单号" width="120" align="center"/>
        <el-table-column prop="pickupCode" label="取餐码" width="120" align="center">
          <template #default="{ row }">
            <span v-if="row.pickupCode" class="pickup-code">{{ row.pickupCode }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="订单状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.orderStatus)" size="small">{{ row.orderStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderTime" label="订单时间" width="180" align="center" :formatter="formatDateTime"/>
        <el-table-column prop="totalAmount" label="订单金额" width="120" align="center" :formatter="formatAmount"/>
        <el-table-column label="备注" min-width="200" align="left">
          <template #default="{ row }">
            <div class="remark-bubble">
              <span v-html="(row.remark || '无')
                      .replace(/null/g, '不添加小料')
                      .replace(/;/g, '<br/>')" />
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="240" align="center">
          <template #default="{ row }">
            <el-button
                v-if="row.orderStatus === '制作中'"
                type="primary"
                size="small"
                @click="updateToPending(row.id)"
                class="btn-space"
            >
              标记待取餐
            </el-button>
            <el-button
                v-else-if="row.orderStatus === '待取餐'"
                type="success"
                size="small"
                @click="updateToCompleted(row.id)"
                class="btn-space"
            >
              标记已完成
            </el-button>
            <el-button
                type="danger"
                size="small"
                @click="goToAbnormalUpload(row)"
            >
              标记异常
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          background
          v-model:current-page="pageContains.pageNum"
          v-model:page-size="pageContains.pageSize"
          :page-sizes="[10,20,30,50,100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageContains.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="orderDialog"
        :title="dialogTitle"
        width="90%"
        max-width="500px"
    >
      <el-form
          ref="orderFormRef"
          :model="curOrder"
          :rules="formRules"
          label-width="100px"
          class="dialog-form"
      >
        <el-form-item v-if="dialogOptType===2" label="订单 ID">
          <el-input v-model="curOrder.id" disabled/>
        </el-form-item>
        <el-form-item v-if="dialogOptType===1" label="订单状态" prop="orderStatus">
          <el-select v-model="curOrder.orderStatus">
            <el-option label="制作中" value="制作中"/>
            <el-option label="待取餐" value="待取餐"/>
            <el-option label="已完成" value="完成"/>
          </el-select>
        </el-form-item>
        <el-form-item label="订单时间" prop="orderTime">
          <el-date-picker
              v-model="curOrder.orderTime"
              type="datetime"
              :disabled="dialogOptType===2"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="订单金额" prop="totalAmount">
          <el-input-number
              v-model="curOrder.totalAmount"
              :min="0.01"
              :precision="2"
              style="width:100%"
          />
        </el-form-item>
        <el-form-item v-if="dialogOptType===2 && curOrder.pickupCode" label="取餐码">
          <el-input v-model="curOrder.pickupCode" disabled/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeOrderDialog">取消</el-button>
        <el-button type="primary" @click="optOne">{{ buttonOpt }}</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
        v-model="detailDialog"
        title="订单详情"
        width="90%"
        max-width="500px"
    >
      <el-form label-width="100px" class="dialog-form">
        <el-form-item label="订单 ID">
          <el-input :value="curOrder.id" disabled/>
        </el-form-item>
        <el-form-item label="取餐码">
          <el-input :value="curOrder.pickupCode||'未生成'" disabled/>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-input :value="curOrder.orderStatus" disabled/>
        </el-form-item>
        <el-form-item label="订单时间">
          <el-input :value="formatDateTime(curOrder,'orderTime')" disabled/>
        </el-form-item>
        <el-form-item label="订单金额">
          <el-input :value="formatAmount(null,null,curOrder.totalAmount)" disabled/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDetailDialog">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/axios/http'

const router = useRouter()

/* 基础数据 */
const orderList = ref([])
const errorMessage = ref('')
const queryOrderStatus = ref('')
const startTime = ref(null), endTime = ref(null)
const orderDialog = ref(false), detailDialog = ref(false)
const dialogTitle = ref(''), buttonOpt = ref(''), dialogOptType = ref(1)  // 1新增 2编辑
const curOrder = ref({})
const orderFormRef = ref()
const pageContains = reactive({ pageNum: 1, pageSize: 10, total: 0 })
const formRules = reactive({
  orderStatus: [{ required: true, message: '请选择订单状态', trigger: 'change' }],
  orderTime: [{ required: true, message: '请选择订单时间', trigger: 'change' }],
  totalAmount: [{ required: true, message: '请输入金额', trigger: 'blur' }, { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur' }]
})

/* 生命周期 */
onMounted(() => getAllOrders())

/* 接口方法 */
function getAllOrders() {
  http.post('/glsb/get_all_orders', {
    pageNum: pageContains.pageNum,
    pageSize: pageContains.pageSize
  }).then(res => {
    if (res.data.result === 'success') {
      Object.assign(pageContains, res.data.data)
      orderList.value = res.data.data.list
    } else {
      errorMessage.value = res.data.error
      ElMessage.error(res.data.error)
    }
  }).catch(e => ElMessage.error('获取订单失败：' + e.message))
}

function queryOrders() {
  // 验证时间范围
  if (startTime.value && endTime.value && new Date(startTime.value) > new Date(endTime.value)) {
    ElMessage.warning('开始时间不能晚于结束时间')
    return
  }

  const param = {
    orderStatus: queryOrderStatus.value || null,
    startTime: startTime.value ? new Date(startTime.value).toISOString() : null,
    endTime: endTime.value ? new Date(endTime.value).toISOString() : null,
    pageNum: pageContains.pageNum,
    pageSize: pageContains.pageSize
  }
  http.post('/glsb/get_orders_by_status_and_time', param).then(res => {
    if (res.data.result === 'success') {
      Object.assign(pageContains, res.data.data)
      orderList.value = res.data.data.list
      ElMessage.success('查询成功')
    } else {
      errorMessage.value = res.data.error
      ElMessage.error(res.data.error)
    }
  }).catch(e => ElMessage.error('查询失败：' + e.message))
}

function getOrderInfo(id) {
  return http.post('/glsb/get_order_by_id', { orderId: id }).then(res => {
    if (res.data.result === 'success') {
      curOrder.value = {
        ...res.data.data,
        orderTime: res.data.data.orderTime ? new Date(res.data.data.orderTime) : null
      }
    } else {
      ElMessage.error(res.data.error)
    }
  })
}

/* 对话框方法 */
function showOrderDialog() {
  dialogTitle.value = '新增订单'
  buttonOpt.value = '新增'
  dialogOptType.value = 1
  curOrder.value = { orderStatus: '制作中', orderTime: new Date() }
  orderDialog.value = true
}

async function showDetailDialog(id) {
  await getOrderInfo(id)
  detailDialog.value = true
}

async function showEditDialog(id) {
  await getOrderInfo(id)
  dialogTitle.value = '订单信息修改'
  buttonOpt.value = '修改'
  dialogOptType.value = 2
  orderDialog.value = true
}

function closeOrderDialog() {
  orderDialog.value = false
  curOrder.value = {}
  orderFormRef.value?.resetFields()
}

function closeDetailDialog() {
  detailDialog.value = false
  curOrder.value = {}
}

/* 提交方法 */
function optOne() {
  orderFormRef.value.validate(valid => {
    if (!valid) return
    dialogOptType.value === 1 ? addOne() : editOne()
  })
}

function addOne() {
  const param = {
    ...curOrder.value,
    orderTime: curOrder.value.orderTime ? new Date(curOrder.value.orderTime).toISOString() : null
  }
  http.post('/glsb/add_one_order', param).then(res => {
    if (res.data.result === 'success') {
      closeOrderDialog()
      getAllOrders()
      ElMessage.success('新增成功')
    } else {
      ElMessage.error(res.data.error)
    }
  }).catch(e => ElMessage.error('新增失败：' + e.message))
}

function editOne() {
  const param = {
    ...curOrder.value,
    orderTime: curOrder.value.orderTime ? new Date(curOrder.value.orderTime).toISOString() : null
  }
  http.post('/glsb/modify_order_by_id', param).then(res => {
    if (res.data.result === 'success') {
      closeOrderDialog()
      getAllOrders()
      ElMessage.success('修改成功')
    } else {
      ElMessage.error(res.data.error)
    }
  }).catch(e => ElMessage.error('修改失败：' + e.message))
}

/* 状态流转方法 */
function updateToPending(id) {
  ElMessageBox.confirm(
      '确定标记为“待取餐”？系统将自动生成取餐码',
      '提示',
      { type: 'info' }
  )
      .then(() => http.post('/glsb/update_order_to_pending', { orderId: id }))
      .then(res => {
        if (res.data.result === 'success') {
          ElMessage.success(`已标记为待取餐，取餐码：${res.data.data.pickupCode}`)
          getAllOrders()
        } else {
          ElMessage.error(res.data.error)
        }
      }).catch(() => ElMessage.info('已取消'))
}

function updateToCompleted(id) {
  ElMessageBox.confirm(
      '确定标记为“已完成”？表示顾客已取餐',
      '提示',
      { type: 'success' }
  )
      .then(() => http.post('/glsb/update_order_to_completed', { orderId: id }))
      .then(res => {
        if (res.data.result === 'success') {
          ElMessage.success('已标记为已完成')
          getAllOrders()
        } else {
          ElMessage.error(res.data.error)
        }
      }).catch(() => ElMessage.info('已取消'))
}

/* 分页方法 */
function handleSizeChange(val) {
  pageContains.pageSize = val
  pageContains.pageNum = 1
  getAllOrders()
}

function handlePageChange(val) {
  pageContains.pageNum = val
  getAllOrders()
}

/* 路由方法 */
function goToScreen() {
  router.push('/screen').catch(() => ElMessage.error('大屏叫号页面不存在'))
}

// 跳转到异常订单上传页
function goToAbnormalUpload(row) {
  try {
    const orderNo = String(row.id)
    const orderTime = row.orderTime instanceof Date ? row.orderTime : new Date(row.orderTime)
    const orderDate = orderTime.toISOString().split('T')[0]

    router.push({
      name: 'abnormal-upload',
      query: { orderNo, orderDate }
    })
  } catch (e) {
    console.error('跳转异常：', e)
    ElMessage.error('跳转失败，请重试')
  }
}

/* 工具方法 */
function getStatusTagType(status) {
  switch (status) {
    case '制作中': return 'warning'
    case '待取餐': return 'primary'
    case '完成': return 'success'
    default: return 'info'
  }
}

function formatDateTime(row, col, val) {
  const v = val || (row && row[col]) || row
  if (!v) return ''

  const date = new Date(v)
  if (isNaN(date.getTime())) return '无效时间'

  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

function formatAmount(row, col, val) {
  const v = val || row?.[col?.property] || 0
  return `¥${Number(v).toFixed(2)}`
}
</script>

<style scoped>
.order-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
}

.search-container {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  align-items: center;
  padding: 15px;
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}

.date-range {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 420px;
}

.date-separator {
  color: #999;
  white-space: nowrap;
}

.error-message {
  color: #f56c6c;
  margin-bottom: 20px;
  padding: 10px 15px;
  background: #fff1f0;
  border-radius: 4px;
  border-left: 4px solid #f56c6c;
}

.table-wrapper {
  background: #fff;
  border-radius: 6px;
  padding: 10px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
  margin-bottom: 20px;
  overflow: hidden;
}

.pickup-code {
  display: inline-block;
  padding: 2px 8px;
  background: #fff2e8;
  color: #ff7d00;
  border-radius: 4px;
  font-weight: bold;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 10px;
  background: #fff;
  border-radius: 6px;
}

.remark-bubble {
  display: inline-block;
  max-width: 100%;
  padding: 4px 10px;
  background: #f0f7ff;
  border: 1px solid #c6e2ff;
  color: #409eff;
  font-size: 12px;
  line-height: 1.4;
  border-radius: 4px;
  word-break: break-all;
}

.btn-space {
  margin-right: 5px;
}

.dialog-form {
  margin-top: 15px;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .date-range {
    width: 340px;
  }
}

@media (max-width: 768px) {
  .search-container {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  .date-range {
    width: 100%;
  }

  .pagination-container {
    justify-content: center;
  }

  .table-wrapper {
    padding: 5px;
  }
}

@media (max-width: 480px) {
  .order-container {
    padding: 10px;
  }

  .date-range {
    flex-direction: column;
    align-items: stretch;
  }

  .date-separator {
    display: none;
  }
}
</style>